package cn.anosi.controller.auth;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.anosi.controller.BaseController;
import cn.anosi.dto.OrganizationDto;
import cn.anosi.entity.auth.Organization;
import cn.anosi.exception.CustomException;
import cn.anosi.page.PageResponseBean;
import cn.anosi.page.Pager;
import cn.anosi.service.auth.OrganizationService;
import cn.anosi.utils.ExcelUtils;
import cn.anosi.vo.OrganizationTree;


@Controller
@RequestMapping("/organization")
public class OrganizationController extends BaseController {

    @Autowired
    protected OrganizationService organizationService;

    /**
     * 列表页面
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return "organization/list";
    }

    /**
     * 列表数据
     *
     * @param pager
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public PageResponseBean<Organization> list(@RequestParam(defaultValue = "1") Integer pId, Pager pager, OrganizationDto dto) {
        return organizationService.list(pager, pId, dto);
    }

    /**
     * 根据id 锁定/启用
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/lock", method = RequestMethod.POST)
    @ResponseBody
    public int lock(Integer id, Integer status) {
        return organizationService.lock(id, status);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public int delete(Integer id) {
        return organizationService.delete(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    @ResponseBody
    public int batchDel(@RequestBody List ids) {
        return organizationService.batcahDel(ids);
    }

    /**
     * 添加页面
     *
     * @return
     */
    @RequestMapping(value = "/add/{pId}", method = RequestMethod.GET)
    public String add(@PathVariable Integer pId, Model model) {
        Organization parent = organizationService.getById(pId);
        model.addAttribute("parent", parent);
        return "organization/add";
    }

    /**
     * 保存
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public int save(Organization organization, Integer pId) {
        Organization parent = organizationService.getById(pId);
        if (null == parent) {
            return 0;
        }

        Organization exist = organizationService.findByName(organization.getName());
        if (exist != null) {
            throw new CustomException("机构名称已存在");
        }

        organization.setParent(parent);
        organization.setIsDel(0);
        organization.setStatus(0);
        organization.setCreateTime(new Date());
        try {
            organizationService.save(organization);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 修改页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Integer id, Model model) {
        Organization organization = organizationService.getById(id);
        model.addAttribute("organization", organization);
        return "organization/edit";
    }

    /**
     * 修改
     *
     * @param organization
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public int edit(Organization organization, Integer pId) throws IllegalAccessException, InvocationTargetException {
        if (null != organization && null != organization.getId()) {
            Organization entity = organizationService.getById(organization.getId());
            entity.setName(organization.getName());
            entity.setDescription(organization.getDescription());
            entity.setIcon(organization.getIcon());
            entity.setEditTime(new Date());
            try {
                organizationService.save(entity);
                organizationService.updateBySql("update organization set p_id = ? where id = ?", pId, entity.getId());
                return 1;
            } catch (Exception e) {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 导出
     *
     * @param entity
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(Organization entity, HttpServletResponse response, Integer pId, OrganizationDto dto) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();


        ArrayList<String> titleList = new ArrayList<String>();
        titleList.add("名称");
        titleList.add("描述");
        String[] title = new String[titleList.size()];
        titleList.toArray(title);

        //标题行
        //String[] title = {"id",  "创建时间", "修改时间"};
        ExcelUtils.setDefaultHead(workbook, sheet, title);

        //数据行
        List<Organization> list = organizationService.list(pId, dto);
        for (Organization organization : list) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            if (organization.getName() != null) {
                dataRow.createCell(titleList.indexOf("名称")).setCellValue(organization.getName());
                if (organization.getName().toString().length() * 256 > sheet.getColumnWidth(titleList.indexOf("名称"))) {
                    sheet.setColumnWidth(titleList.indexOf("名称"), organization.getName().toString().length() * 256);
                }
            }
            if (organization.getDescription() != null) {
                dataRow.createCell(titleList.indexOf("描述")).setCellValue(organization.getDescription());
                if (organization.getDescription().toString().length() * 256 > sheet.getColumnWidth(titleList.indexOf("描述"))) {
                    sheet.setColumnWidth(titleList.indexOf("描述"), organization.getDescription().toString().length() * 256);
                }
            }
        }

        String fileName = new String("组织机构列表.xls".getBytes("GB2312"), "ISO_8859_1");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        ServletOutputStream os = response.getOutputStream();
        workbook.write(os);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping(value = "/importXls", method = RequestMethod.POST)
    @ResponseBody
    public int importXls(@RequestParam MultipartFile file, Integer pId) throws IOException, ParseException {
        HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
        HSSFSheet sheet = workbook.getSheetAt(0);
        ArrayList<Organization> list = new ArrayList<Organization>();

        ArrayList<String> titleList = new ArrayList<String>();
        titleList.add("名称");
        titleList.add("描述");

        Organization parent = organizationService.getById(pId);
        for (Row row : sheet) {
            int rowNum = row.getRowNum();
            if (rowNum == 0) {
                continue;
            }

            Organization organization = new Organization();
            organization.setName(row.getCell(titleList.indexOf("名称")).getStringCellValue());
            organization.setDescription(row.getCell(titleList.indexOf("描述")).getStringCellValue());
            organization.setCreateTime(new Date());
            organization.setStatus(0);
            organization.setIsDel(0);
            organization.setParent(parent);
            list.add(organization);
        }
        if (list.size() > 0) {
            return organizationService.batchSave(list);
        } else {
            return 0;
        }
    }

    /**
     * 组织机构树
     *
     * @return
     */
    @RequestMapping(value = "/tree", method = RequestMethod.POST)
    @ResponseBody
    public List<OrganizationTree> tree() {
        return organizationService.tree();
    }

    /**
     * 除当前机构以外的其他机构列表
     *
     * @return
     */
    @RequestMapping(value = "others", method = RequestMethod.POST)
    @ResponseBody
    public List<Organization> others(Integer id) {
        return organizationService.others(id);
    }
}
